package service

import (
	"counter-help/admin/server/global"
	picModel "counter-help/admin/server/plugin/picturelibrary/model"
	"github.com/gin-gonic/gin"
	"strings"
)

type PictureLibraryService struct{}

func (e *PictureLibraryService) PlugService() (err error) {
	// 写你的业务逻辑
	return nil
}

func (e *PictureLibraryService) GetFileRecordInfoList(info picModel.PageInfo, c *gin.Context) (list interface{}, total int64, err error) {
	limit := info.Limit
	offset := info.Limit * (info.Page - 1)
	keyword := info.Keyword
	cid := info.Cid
	db := global.GVA_DB.Model(&picModel.SysAttachment{})
	var fileLists []picModel.SysAttachment
	if len(keyword) > 0 {
		db = db.Where("`name` LIKE ?", "%"+keyword+"%")
	}
	if cid > 0 {
		db = db.Where("cat_id = ?", cid)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Order("created_at desc").Find(&fileLists).Error
	urlHost := e.GetUrlHost(c)
	for k, v := range fileLists {
		if !strings.HasPrefix(v.Url, "http://") && !strings.HasPrefix(v.Url, "https://") {
			v.Url = urlHost + "api/" + v.Url
			fileLists[k] = v
		}
	}
	return fileLists, total, err
}

// 构建树形结构
func (e *PictureLibraryService) BuildTree(categories []picModel.SysAttachmentCategory, parentID uint) []*picModel.SysAttachmentCategory {
	var tree []*picModel.SysAttachmentCategory
	for _, category := range categories {
		if category.Pid == parentID {
			children := e.BuildTree(categories, category.Id)
			category.Children = children
			tree = append(tree, &category)
		}
	}
	return tree
}

func (e *PictureLibraryService) GetUrlHost(c *gin.Context) string {
	host := c.Request.Host
	scheme := "http"
	if c.Request.TLS != nil {
		scheme = "https"
	}
	referer := c.Request.Referer()
	if referer != "" {
		return referer
	}
	return scheme + "://" + host + "/"
}
